# -*- coding: utf-8 -*-
# @Author  : JackRoc
# @FileName: jd.py
import random
import time
from selenium.webdriver import ActionChains

from collections import Counter
from PIL import Image

from selenium import webdriver





# login_button //*[@class="user_login"]
# accent_login_button   //div[@class="login-tab login-tab-r"]/a
# account_input   id  loginname
# password_input  id nloginpwd
# login_button    id loginsubmit



def login(account, pwd):
    # time.sleep(2)
    # driver.find_element_by_xpath('//*[@class="user_login"]').click()
    time.sleep(2)
    driver.find_element_by_xpath('//div[@class="login-tab login-tab-r"]/a').click()
    time.sleep(2)
    driver.find_element_by_id('loginname').send_keys(account)
    time.sleep(2)
    driver.find_element_by_id('nloginpwd').send_keys(pwd)
    time.sleep(2)
    driver.find_element_by_id('loginsubmit').click()
    time.sleep(2)

def get_img(num,driver):
    js_none = "document.getElementsByClassName('JDJRV-smallimg')[0].style.display='none';"
    driver.execute_script(js_none)
    time.sleep(1)
    driver.find_element_by_xpath('//*[@id="JDJRV-wrap-loginsubmit"]/div/div/div/div[1]/div[2]/div[1]/img').screenshot('{}.png'.format(num))
    #                             //*[@id="JDJRV-wrap-loginsubmit"]/div/div/div/div[1]/div[2]/div[1]/img
    img = Image.open('{}.png'.format(num))
    js_block = "document.getElementsByClassName('JDJRV-smallimg')[0].style.display='block';"
    driver.execute_script(js_block)
    time.sleep(1)
    return img

# 灰度处理
def converGrey(image):
    img = image.convert('L')
    # img.show()
    return img

# 二值化
def binaring(image):
    total = []
    pixel = image.load()
    for x in range(image.size[0]):
        for y in range(image.size[1]):
            total.append(pixel[x, y])
    avg = sum(total) // len(total) * 0.618

    for x in range(image.size[0]):
        for y in range(image.size[1]):
            if pixel[x, y] < avg:
                pixel[x ,y] = 0
            else:
                pixel[x, y] = 255
    return image

# 降噪
def depoint(img):
    pixel = img.load()
    for x in range(1, img.size[0] - 1):
        for y in range(1, img.size[1] -1):
            count = 0
            if pixel[x, y-1] > 200:
                count += 1
            if pixel[x, y+1] > 200:
                count += 1
            if pixel[x-1, y] > 200:
                count += 1
            if pixel[x+1, y] > 200:
                count += 1
            if pixel[x-1, y-1] > 200:
                count += 1
            if pixel[x-1, y+1] > 200:
                count += 1
            if pixel[x+1, y-1] > 200:
                count += 1
            if pixel[x+1, y+1] > 200:
                count += 1
            if count > 4:
                pixel[x, y] = 255
    img.show()
    return img

def check(img):
    pixel = img.load()
    ls = []
    for i in range(54, 151):
        for j in range(19, 108):
            if pixel[i, j] < 100:
                count = 0
                for k in range(30):
                    if pixel[i+k, j] < 200:
                        count += 1
                if count > 27:
                    ls.append(i)
    counter = Counter(ls)
    x = counter.most_common(1)[0][0]
    return x

def get_track(distance):
    # 初速度
    v = 0
    # 单位时间为0.2秒来统计轨迹 轨迹即0.2内的位移
    t = 0.2
    # 位移/轨迹列表，列表内的一个元素代表0.2s的位移
    tracks = []
    # 当前的位移
    current = 0
    # 到达mid值开始减速
    mid = distance * 4 / 5
    # distance += 10 # 先滑过一点。最后再反着滑动回来
    while current < distance:
        if current < mid:
            # 加速度越小，单位时间的位移越小，模拟的轨迹就越多越详细
            a = random.uniform(3,5)    # 加速运动
        else:
            a = -(random.uniform(12.5, 13.5))   # 减速运动
        # 初速度
        v0 = v
        # 0.2s时间内的位移
        s = v0 * t + 0.5 * a * (t ** 2)
        # 速度已将达到v，该速度作为下次的初速度
        v = v0 + a * t
        # 当前的位置
        current += s
        # 添加到轨迹列表
        if 0.6 < current - distance < 1:
            s = s - 0.53
            tracks.append(round(s))
        elif 1 < current - distance < 1.5:
            s = s - 1.4
            tracks.append(round(s))
        elif 1.5 < current - distance < 3:
            s = s - 1.8
            tracks.append(round(s))
        else:
            tracks.append(round(s))


        #

    return tracks

def main(driver, elem , img):
    x = check(img)
    print(x)

    action = ActionChains(driver)
    tracks = get_track(x)
    ActionChains(driver).click_and_hold(elem).perform()
    for x in tracks:
        ActionChains(driver).move_by_offset(xoffset=x, yoffset=0).perform()
        # 新建ActionChains对象防止累加位移
        action = ActionChains(driver)
    time.sleep(0.5)
    action.release(elem).perform()

    time.sleep(3)

if __name__ == '__main__':
    options = webdriver.ChromeOptions()
    options.add_argument('--ignore-certificate-errors')
    driver = webdriver.Chrome(options=options)
    driver.maximize_window()
    driver.get('https://passport.jd.com/new/login.aspx')
    login('aaaaaaa', 'aaaaaaaaa')
    time.sleep(2)
    for i in range(4,15):
        img = get_img(i,driver)
        # img.show()

        # img = Image.open('1.png')
        img = converGrey(img)
        # img.show()
        img = binaring(img)
        # img.show()
        img = depoint(img)
        elem =driver.find_element_by_xpath('//*[@id="JDJRV-wrap-loginsubmit"]/div/div/div/div[2]/div[3]')

        main(driver, elem, img)